﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Business.Util;
using ZLCMS.Data.Model;
using NHibernate.Criterion;
using ZLCMS.Business.TranferParam;
using ZLCMS.Web.SystemManage.Control;
using System.Collections.Generic;
using Newtonsoft.Json;
using NHibernate;
using DotNet.Common.TransferParam;
using ZLCMS.Business.Shop.Data;

namespace ZLCMS.Web.SystemManage.Basics
{
    public partial class MealEdit : System.Web.UI.Page
    {
        protected FrameHelper _framePage;
        public string _userAccount;
        protected ShopProductInfo _productDB;

        private List<ProductCustomData> _dataList;

        protected void Page_Load(object sender, EventArgs e)
        {
            //初始化DWZ控件
            _framePage = new FrameHelper(this);
            _userAccount = UserKit.GetUserAccountFailLogin();

            //初始化全局变量值
            InitializeGlobalValue();

            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                SaveUser();
            }
        }

        #region 初始化全局变量 + protected void InitializeGlobalValue()
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        protected void InitializeGlobalValue()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                try
                {
                    if (!IsPostBack)
                    {
                        _id.Text = Request["pid"];
                    }

                    _productDB = session.Get<ShopProductInfo>(int.Parse(_id.Text));

                    if (_productDB == null)
                    {
                        throw new Exception("找不到对应信息.");
                    }

                    if (!IsPostBack)
                    {
                        ShopCategory node = null;

                        if (_productDB.TypeId != 0)
                        {
                            node = session.Get<ShopCategory>(_productDB.TypeId);
                        }
                        if (node != null)
                        {
                            ddl_producttype.SelectedNodeId = node.Id;
                            ddl_producttype.SelectedNodeText = node.CategoryName;
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }
        }
        #endregion

        #region 初始化产品信息 + 初始化产品信息
        /// <summary>
        /// 初始化产品信息
        /// </summary>
        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                tb_name.Text = _productDB.ProductName;
                tb_productno.Text = _productDB.ProductNo;

                tb_shortdesc.Text = _productDB.ShortDesc;
                tb_sprice.Text = _productDB.SalePrice.ToString();

                if (_productDB.IsCommend == "1")
                {
                    cbxCommend.Checked = true;
                }
                else
                {
                    cbxCommend.Checked = false;
                }

                fc_open.Value = _productDB.ThumbnailImg;
                fc_open.Config = new Business.UploadFileInfo.UploadConfig()
                {
                    Thumbnail = new ThumbnailConfig()
                    {
                        Mode = "HW",
                        Auto = true,
                        Name = ".thumb.jpg",
                        Height = 100,
                        Width = 100
                    },
                    UploadDir = _userAccount + "/product/"
                };


                txt_description.Value = _productDB.Description;

                if (_productDB.CustomField != null)
                {
                    _dataList = JsonConvert.DeserializeObject<List<ProductCustomData>>(_productDB.CustomField);
                }


            }
        }
        #endregion

        #region 保存产品 + protected void SaveUser()
        /// <summary>
        /// 保存产品
        /// </summary>
        protected void SaveUser()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                if (string.IsNullOrEmpty(tb_name.Text) || string.IsNullOrEmpty(tb_productno.Text))
                {
                    _framePage.Alert(new ReturnCode()
                    {
                        statusCode = 300,
                        message = "参数错误!",
                        callbackType = "closeCurrent",
                        navTabId = _framePage.NavTabId
                    });
                }
                else
                {
                    int _count = Convert.ToInt32(session.CreateSQLQuery("select count(*) from SHOP_PRODUCT_INFO where PRODUCT_NO='" + tb_productno.Text + "' and OWNER_ACCOUNT='" + _userAccount + "' and KIND='restaurant' and ID!=" + _productDB.Id).UniqueResult());
                    if (_count>0)     
                    {
                        _framePage.Alert(new ReturnCode()
                   {
                       statusCode = 300,
                       message = "该产品编号已存在!",
                       callbackType = "closeCurrent",
                       navTabId = _framePage.NavTabId
                   });
                    }
                    else
                    {
                        _productDB.ProductName = tb_name.Text;
                        _productDB.ProductNo = tb_productno.Text;

                        _productDB.CustomField = GetCustomString();
                        _productDB.TypeId = ddl_producttype.SelectedNodeId;

                        _productDB.ShortDesc = tb_shortdesc.Text;
                        _productDB.SalePrice = decimal.Parse(tb_sprice.Text);

                        _productDB.Score = 0;
                        _productDB.Coins = 0;

                        _productDB.IsForSale = "0";
                        _productDB.IsCommend = "0";
                        _productDB.IsHot = "0";
                        _productDB.IsSpecialOffer = "0";
                        _productDB.IsVirtual = "0";

                        _productDB.AddTime = DateTime.Now;
                        _productDB.Hits = 0;
                        _productDB.ThumbnailImg = fc_open.Value;

                        if (cbxCommend.Checked == true)
                        {
                            _productDB.IsCommend = "1";
                        }
                        else
                        {
                            _productDB.IsCommend = "0";
                        }
                        _productDB.Description = txt_description.Value;
                        // _productDB.PackContent = txt_bzqd.Value;
                        // _productDB.ParamContent = txt_spcs.Value;
                        // _productDB.GiftContent = txt_zengs.Value;
                        _productDB.OwnerAccount = _userAccount;

                        session.Update(_productDB);
                        session.Flush();

                        _framePage.Alert(new ReturnCode()
                        {
                            statusCode = 200,
                            message = "操作成功!",
                            callbackType = "closeCurrent",
                            navTabId = _framePage.NavTabId
                        });
                    }
                }
            }
        }
        #endregion

        #region 绑定rp_pjlb + protected void rp_pjlb_ItemDataBound(object sender, RepeaterItemEventArgs e)
        /// <summary>
        /// 绑定rp_pjlb
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rp_pjlb_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            Label lbId = (Label)e.Item.FindControl("lb_pjid");
            CheckBoxControl cblist = (CheckBoxControl)e.Item.FindControl("cbc_list");

            System.Collections.Generic.List<ParamFilterCondition> list = new System.Collections.Generic.List<ParamFilterCondition>();

            //获取绑定的 Productcustomfield 每一项
            ShopCustomField item = (ShopCustomField)e.Item.DataItem;

            lbId.Text = item.Id.ToString();
            list.Add(new ParamFilterCondition() { Code = "Field", Value = item.Id.ToString() });

            if (_dataList != null)
            {
                foreach (ProductCustomData dataItem in _dataList)
                {
                    // 类别一致
                    if (dataItem.FieldKind == item.Id)
                    {
                        ParamKit.Bind("ProductCustomField", cblist.DataList, list, null, null, dataItem.FieldSelected, null);
                        return;
                    }
                }
            }

            // 无匹配类别
            ParamKit.Bind("ProductCustomField", cblist.DataList, list, null, null, null, null);
        }
        #endregion

        #region 获取定制属性内容 + protected string GetCustomString()
        /// <summary>
        /// 获取定制属性内容
        /// </summary>
        /// <returns></returns>
        protected string GetCustomString()
        {
            //Label lbId;
            //CheckBoxControl chkblist;

            //List<ProductCustomData> dataList = new List<ProductCustomData>();

            //foreach (RepeaterItem item in rp_pjlb.Items)
            //{
            //    lbId = (Label)item.FindControl("lb_pjid");
            //    chkblist = (CheckBoxControl)item.FindControl("cbc_list");

            //    if (!string.IsNullOrEmpty(chkblist.SelectedValue))
            //    {
            //        dataList.Add(new ProductCustomData() { FieldKind = int.Parse(lbId.Text), FieldSelected = chkblist.SelectedValue });
            //    }
            //}

            //return JsonConvert.SerializeObject(dataList);
            return null;
        }
        #endregion
    }
}
